﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Collections.Specialized;

public class Code
{
    static void Main2()
    {


        Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        string str;
        sk.Connect(new IPEndPoint(IPAddress.Parse("192.168.2.50"), 21));
        NetworkStream ns = new NetworkStream(sk);
        StreamWriter sw = new StreamWriter(ns, Encoding.ASCII);
        StreamReader sr = new StreamReader(ns, Encoding.ASCII);
        sw.Write("USER fastcgi\r\n");
        sw.Flush();
        str = sr.ReadLine();
        Console.WriteLine(str);
        sw.Write("PASS 123MessageCodeLength56\r\n");
        sw.Flush();
        str = sr.ReadLine();
        Console.WriteLine(str);


        sw.Write("USER fastcgi\r\n");
        sw.Flush();
        str = sr.ReadLine();
        Console.WriteLine(str);
        sw.Write("PASS 123MessageCodeLength56\r\n");
        sw.Flush();
        str = sr.ReadLine();
        Console.WriteLine(str);

        Console.ReadLine();
        return;
    }
    static char IPFORMATESPLIT=',';

    static string GetModeFromFileExtense(string fileExtense)
    {
        if (fileExtense == null || fileExtense.Length == 0)
        {
            return "i";
        }
        if (fileExtense.EndsWith(".txt") ||
            fileExtense.EndsWith(".c") ||
            fileExtense.EndsWith(".cc") ||
            fileExtense.EndsWith(".php") ||
            fileExtense.EndsWith(".js") ||
            fileExtense.EndsWith(".css"))
        {
            return "t";
        }
        return null;
    }
    
    static string FormateIPEndPoint(IPEndPoint ip)
    {
        StringBuilder sb = null;
        long l = ip.Address.Address;
        for (int i = 1; i <= 4; i++)
        {
            if (sb == null)
            {
                sb = new StringBuilder();
            }
            else
            {
                sb.Append(IPFORMATESPLIT);
            }
            sb.Append(l & 255);
            l = l >> 8;
        }
        sb.Append(string.Format(",{1},{0}", ip.Port & 255, ip.Port >> 8));
        return sb.ToString();
    }
    static void Main1()
    {

        Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        
        sk.Connect(IPAddress.Parse("127.0.0.1"), 80);

        NetworkStream ns = new NetworkStream(sk);

        StreamWriter sw = new StreamWriter(ns, Encoding.ASCII);
        sw.WriteLine(@"GET /advertisement/admin/select_list/ HTTP/1.1
Host: www.158.com
User-Agent: Mozilla/5.0 (Windows NT 5.2; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Cookie: PHPSESSID=qif32lk53s2jk7l5fgvkobb554; gyw_r_uname=Fireman_duck%40126.com; gyw__user_login=7tfM7NHeyeDLyNKdqtvd3tHI6NHU3dbRqqakmqDO6NGItZ_gyebZ4eTkyNDIpMrIsKbTy9nHzafTlaifrJWg3diintaXzqmpxdadrcfKm62d3dzKyNKdmaiMtJG8u9DNk8DV5N7e0NOarpKXmprH0eHK2ezlhMC_mZmVrK2Q2umgm6qglJuLwMnK5eGfmqOXmqWjlKOLv83Z39jf4KKXn6OikqM.; CNZZDATA4330389=cnzz_eid=32034748-1348218308-&ntime=1348218308&cnzz_a=1&retime=1348218325906&sin=&ltime=1348218325906&rtime=0
Cache-Control: max-age=0");
        sw.WriteLine();
        sw.Flush();

        string filepath = "C:\\index.htm";

        FileStream fs;
        if (File.Exists(filepath))
        {
            fs=  new FileStream(filepath, FileMode.Truncate, FileAccess.Write);
        }else{
            fs = new FileStream(filepath, FileMode.Create, FileAccess.Write);
        }


        byte[] buff=new byte[1024];
        int len=ns.Read(buff,0,buff.Length);

        while (len > 0)
        {
            fs.Write(buff, 0, len);
            len = ns.Read(buff, 0, buff.Length);
        }
        fs.Close();
        fs.Dispose();
        return;

        //sk.ReceiveTimeout = 10;
        //byte[] buff = new byte[1024];
        //int len;
        //try
        //{ len= sk.Receive(buff);
        //}catch(Exception){
        //    sk.ReceiveTimeout = 1000;
        //   len = sk.Receive(buff);
        //}
        //for (int i = 0; i < 10; i++)
        //{
        //    byte[] rd = new byte[len];
        //    for (int j = 0; j < len; j++)
        //    {
        //        rd[j] = buff[j];
        //    }
        //    Console.WriteLine(Encoding.ASCII.GetString(rd));
        //    Console.ReadLine();
        //}
        //return;

        //foreach (IPAddress i in Dns.GetHostAddresses(Dns.GetHostName()))
        //{
        //    Socket s=new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    s.Bind(new IPEndPoint(i, 20000));
        //    s.Listen(5);
        //    NetworkStream ns = new NetworkStream(s.Accept());
        //    StreamReader sr = new StreamReader(ns);
        //    Console.Write(sr.ReadToEnd());
        //    Console.Read();
        //    return;
        //}

        //var o = new WebCamService.FtpClient();
        //o.Username = "root";
        //o.Password = "123456";
        //o.Login();
        //foreach (string i in o.GetFileList())
        //{
        //    Console.WriteLine(i);
        //}
        //Console.Read();
        //return;


        //FileStream fs = new FileStream("c:\\z.7z", FileMode.Open);

        FTP.ClientCommand cc = new FTP.ClientCommand("192.168.2.50", "fastcgi", "123456");
        //FTP.ClientCommand cc = new FTP.ClientCommand("127.0.0.1", "root", "123456");
        cc.Login();
        //cc.Directory_Change("1");
        //cc.Directory_Delete("555");
        //cc.File_Uping("z.7z", fs);
        Console.WriteLine(cc.Directory_Current());
        Console.Write( cc.Directory_List("/"));
        Console.ReadLine();
    }

    static void Main()
    {
        FTP.ClientCommand cb = new FTP.ClientCommand("192.168.2.50", 21, "fastcgi", "123456");
        cb.Login();
        Console.Write(cb.Directory_List(null));
        Console.Read();
    }

}
/*
namespace Fireman_FTP
{
    class FTPClient
    {

        const char SPACECHAR = (char)32;

        public IPEndPoint IPPoint;

        public string USER;

        public bool IsConnection;
        public bool IsLogin;

        protected StringCollection sd = null;

        public StreamFTPCMD cmdTP;

        private CommandStatus cmdStatus;

        private string DIR;

        protected FTPClient()
        {
            this.IsConnection = false;
            this.IsLogin = false;
            CommandBaseIni();
        }

        protected void CommandBaseIni()
        {
            if (sd == null)
                sd = new StringCollection();
            sd.Clear();
            sd.Add("USER");
            sd.Add("PASS");
            sd.Add("HELP");
        }

        protected bool CommandBaseContain(string Command)
        {
            if (sd == null)
                return false;
            return sd.Contains(Command);
        }

        public FTPClient(string ip, string port)
            : this()
        {
            IPPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
            cmdTP = new StreamFTPCMD(IPPoint);
            CommandStatus fcs;
            fcs = cmdTP.ReadStatus();
            if (fcs.StatusCode != 220)
            {
                throw new Exception();
            }
            this.IsConnection = true;
        }

        public FTPClient(string ip, string port, string user)
            : this(ip, port)
        {
            this.USER = user;
        }

        public bool Login(string user, string pass)
        {
            this.USER = user;
            return Login(pass);
        }

        public bool Login(string pass)
        {
            if (!this.IsConnection)
                return false;
            if (this.IsLogin)
                return true;
            CommandStatus cs;
            if (!CommandBaseContain("USER"))
                return false;
            cmdTP.Send(string.Format("USER {0}", this.USER));
            cs = cmdTP.ReadStatus();
            if (cs.StatusCode != 331)
                return false;
            if (!CommandBaseContain("PASS"))
                return false;
            cmdTP.Send(string.Format("PASS {0}", pass));
            cs = cmdTP.ReadStatus();
            return true;
        }

        

        public StringCollection LIST()
        {
            StreamFTPData bs;
            CommandStatus cs;
            if (CommandBaseContain("PASV"))
            {
                cmdTP.Send("PASV");
                cs = cmdTP.ReadStatus();
                if (cs.StatusCode != 227)
                {
                    return null;
                }
                bs = new StreamFTPDataPASV(GETFormateIPEndPoint(cs.StatusMessage));
            }
            else if (CommandBaseContain("PORT"))
            {
                bs = new StreamFTPDataFORT(null);
            }
            else
            {
                return null;
            }

            if (!CommandBaseContain("LIST"))
                return null;
            cmdTP.Send("LIST");
            cs = cmdTP.ReadStatus();
            if (cs.StatusCode != 150)
            {
                return null;
            }
            StringCollection sc = new StringCollection();
            string s = bs.Read();
            while (s != null)
            {
                sc.Add(s);
                s = bs.Read();
            }
            cs = cmdTP.ReadStatus();
            if (cs.StatusCode != 226)
            {
                return null;
            }
            return sc;
        }

        public bool MakeDir(string DirName)
        {
            if (!CommandBaseContain("MKD"))
                return false;
            cmdTP.Send("MKD");
            cmdStatus = cmdTP.ReadStatus();
            if (cmdStatus.StatusCode != 257)
            {
                return false;
            }
            return true;
        }

        public bool ChangeDir(string DirName)
        {
            if (!CommandBaseContain("CWD"))
                return false;
            cmdTP.Send("CWD " + DirName);
            cmdStatus = cmdTP.ReadStatus();
            if (cmdStatus.StatusCode != 257)
            {
                return false;
            }
            return true;
        }

        public string CurrentDir()
        {
            if (!CommandBaseContain("PWD"))
                return null;
            cmdStatus = cmdTP.ReadStatus();
            if (cmdStatus.StatusCode == 257)
            {
                //string p = cmdStatus.StatusMessage;
                return cmdStatus.StatusMessage.Substring(1, cmdStatus.StatusMessage.Length - 2);
            }
            return null;

        }

        public void Help()
        {
            if (!CommandBaseContain("HELP"))
                return;
            cmdTP.Send("HELP");
            CommandStatus fcs = cmdTP.ReadStatus();
            if (fcs.StatusCode == 21MessageCodeLength)
            {
                string r = cmdTP.Read();
                CommandBaseIni();
                while (!r.StartsWith("21MessageCodeLength "))
                {
                    foreach (string i in r.Split(new char[] { SPACECHAR }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        sd.Add(i);
                    }
                    r = cmdTP.Read();
                }
            }
            return;
        }
    }

    abstract class BaseStream
    {
        protected NetworkStream bStream;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="IP"></param>
        /// <param name="Type">0:connect,1:listen</param>
        protected BaseStream(IPEndPoint IP, EnumFTPNetWorkLinkType Type)
        {
            Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            skt.Blocking = true;
            if (Type == EnumFTPNetWorkLinkType.PASV)
            {
                skt.Connect(IP);
            }
            else if (Type == EnumFTPNetWorkLinkType.FORT)
            {
                skt.Listen(5);
            }
            bStream = new NetworkStream(skt);
        }

        protected int Read(byte[] buffer, int offset, int size)
        {
            return bStream.Read(buffer, offset, size);
        }

        protected void Write(byte[] buffer, int offset, int size)
        {
            bStream.Write(buffer, offset, size);
        }
    }

    interface IStreamFTPTextIO
    {
        string Read();
        void Send(string val);
    }

    class StreamFTPCMD : BaseStream, IStreamFTPTextIO
    {
        private StreamWriter sw;
        private StreamReader sr;

        public StreamFTPCMD(IPEndPoint IPPoint)
            : base(IPPoint, EnumFTPNetWorkLinkType.PASV)
        {
            sw = new StreamWriter(bStream);
            sr = new StreamReader(bStream);
        }

        public CommandStatus ReadStatus()
        {
            return new CommandStatus(Read());
        }

        public string Read()
        {
            return sr.ReadLine();
        }

        public void Send(string cmd)
        {
            sw.Write(cmd); sw.Write("\r\n");
            sw.Flush();
        }
    }

    class StreamFTPData : BaseStream, IStreamFTPTextIO
    {
        private StreamWriter sw;
        private StreamReader sr;

        public StreamFTPData(IPEndPoint IPPoint, EnumFTPNetWorkLinkType type)
            : base(IPPoint, type)
        {
            sw = new StreamWriter(bStream);
            sr = new StreamReader(bStream);
        }

        public string Read()
        {
            if (sr.BaseStream.CanRead)
                return sr.ReadLine();
            return null;
        }

        public void Send(string cmd)
        {
            if (!sw.BaseStream.CanWrite)
                return;
            sw.Write(cmd); sw.Write("\r\n");
        }
    }

    class StreamFTPDataPASV : StreamFTPData
    {
        public StreamFTPDataPASV(IPEndPoint IPPoint)
            : base(IPPoint, EnumFTPNetWorkLinkType.PASV)
        {
        }
    }

    class StreamFTPDataFORT : StreamFTPData
    {
        public StreamFTPDataFORT(IPEndPoint IPPoint)
            : base(IPPoint, EnumFTPNetWorkLinkType.FORT)
        {

        }
    }
    //


    struct CommandStatus
    {
        public int StatusCode;
        public string StatusMessage;

        public CommandStatus(string cmdline)
        {
            if (cmdline == null || cmdline.Length < MessageCodeLength)
            {
                this.StatusCode = 0;
                this.StatusMessage = null;
            }
            else
            {
                this.StatusCode = int.Parse(cmdline.Substring(0, 3));
                this.StatusMessage = cmdline.Substring(MessageCodeLength);
            }
        }
    }

    enum EnumFTPNetWorkLinkType : byte
    {
        NONE = 0, PASV = 1, FORT = 2
    }

    enum EnumFTPServerToClientType : byte
    {
        NONE = 0, Win2Win = 1, Win2Unix = 2, Win2Mac = 3
    }
}
*/

namespace FTP
{
    public static class FTPCommandHelp
    {
        public const int FTPMessageCodeLength = 4;
        public const char IPFORMATESPLIT = ',';


        public static int RandIPPort()
        {
            return new Random().Next(9999, 19999);
        }

        public static bool IsMatchCode(string message, string match)
        {
            return (message != null && message.Length >= FTPMessageCodeLength && message.StartsWith(match));
        }

        public static string FormateIPEndPoint(IPEndPoint ip)
        {
            StringBuilder sb = null;
            long l = ip.Address.Address;
            for (int i = 1; i <= 4; i++)
            {
                if (sb == null)
                {
                    sb = new StringBuilder();
                }
                else
                {
                    sb.Append(IPFORMATESPLIT);
                }
                sb.Append(l & 255);
                l = l >> 8;
            }
            sb.Append(string.Format(",{1},{0}", ip.Port & 255, ip.Port >> 8));
            return sb.ToString();
        }
        
        public static IPEndPoint GETFormateIPEndPoint(string txt)
        {
            int ip = 0;
            int pt = 0;

            int i = 0;
            int s = 0;
            int p = 0;

            bool b = false;
            bool e = false;

            if (txt == null)
                return null;
            foreach (char c in txt)
            {
                if (c == '(' && !b) { b = true; }
                else if (c == ')')
                {
                    pt += p;
                    p = 0;
                    e = true;
                    break;
                }
                else if (b)
                {
                    if (char.IsNumber(c))
                    {
                        switch (s)
                        {
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                                i *= 10;
                                i += (int)(c - '0');
                                break;
                            case 4:
                            case 5:
                                p *= 10;
                                p += (int)(c - '0');
                                break;
                        }
                    }
                    else //if (c == ',')
                    {
                        switch (s)
                        {
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                                ip += i << (8 * s);
                                i = 0;
                                break;
                            case 4:
                                pt += p << 8;
                                p = 0;
                                break;
                            case 5:
                                pt += p;
                                p = 0;
                                break;
                        }
                        s++;
                    }
                }
            }
            if (!b || !e || ip == 0)
                return null;
            else
                return new IPEndPoint(ip, pt);
        }
    }

    public class ClientBase
    {

        #region Base Element

        protected NetworkCredential netCredential;
        protected Socket clientSocket;
        protected Encoding netEncoding;
        protected StreamReader streamReader;
        protected StreamWriter streamWriter;

        public bool isLogin;

        public string Message_Send;
        public string Message_Recive;

        public StringCollection Message_Pool_Send = new StringCollection();
        public StringCollection Message_Pool_Recive = new StringCollection();


        char[] charbuff = new char[1024];

        /// <summary>
        /// 发送消息到远程主机 或则 返回远程主机消息
        /// 发送值存在Message_Send
        /// 返回值存在Message_Recive
        /// </summary>
        public string Message
        {
            //get
            //{
            //    int i = Message_Pool_Recive.Count;
            //    Message_Recive = null;
            //    while (i > 1)
            //    {
            //        Message_Recive = Message_Pool_Recive[0];
            //        Message_Pool_Recive.RemoveAt(0);
            //    }
            //    return Message_Recive;
            //}
            //set
            //{
            //    Message_Send = value;
            //    Message_Pool_Send.Add(value);
            //}
            get
            {
                Message_Recive = streamReader.ReadLine();
                return Message_Recive;
            }
            set
            {
                Message_Send = value;
                streamWriter.WriteLine(Message_Send);
                streamWriter.Flush();
            }
        }

        #endregion

        public int Port;

        protected virtual string WelcomeMessage()
        {
            if (FTPCommandHelp.IsMatchCode(Message, "22"))
            {
                return Message_Recive.Substring(FTPCommandHelp.FTPMessageCodeLength);
            }
            throw new Exception("Connection Link Error");
        }

        protected virtual string Quite()
        {
            Message = "quit";
            if (FTPCommandHelp.IsMatchCode(Message,"22"))
            {
                return Message_Recive.Substring(FTPCommandHelp.FTPMessageCodeLength);
            }
            throw new Exception("Quite Error");
        }

        #region New

        public ClientBase(string url, int port, string username, string userpassword, Encoding encoding)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(IPAddress.Parse(url), port);

            netCredential = new NetworkCredential(username, userpassword, url);

            Encoding netEncoding = encoding;
            NetworkStream netStream = new NetworkStream(clientSocket);
            streamReader = new StreamReader(netStream, netEncoding);
            streamWriter = new StreamWriter(netStream, netEncoding);

            //EventHandler event_Message_Sender = new EventHandler(Event_Message_Sender);
            //EventHandler event_Message_Receive = new EventHandler(Event_Message_Receive);

            //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Sync_Message_Sender), new StreamReader(netStream, encoding));
            //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Sync_Message_Receive), new StreamWriter(netStream, encoding));

            WelcomeMessage();

            isLogin = false;
        }

        void Sync_Message_Sender(object sender)
        {
            StreamReader sr = sender as StreamReader;
            while (sr.BaseStream.CanRead)
            {
                
            }
        }

        void Sync_Message_Receive(object sender)
        {
        }

        void Event_Message_Sender(object sender, EventHandler e)
        {
            StreamWriter sw = sender as StreamWriter;
            //
        }

        void Event_Message_Receive(object sender, EventHandler e)
        {
            StreamReader sr = sender as StreamReader;
            sr.ReadLine();

        }

        public ClientBase(string url, int port, string username, string userpassword) : this(url, port, username, userpassword, Encoding.ASCII) { }

        public ClientBase(string url, int port) : this(url, port, "anonymous", "anonymous") { }

        public ClientBase(string url, string username, string userpassword) : this(url, 21, username, userpassword, Encoding.ASCII) { }

        #endregion

        public string UserName
        {
            get
            {
                return netCredential.UserName;
            }
            set
            {
                netCredential.UserName = value;
            }
        }
        public string Password
        {
            get
            {
                return netCredential.Password;
            }
            set
            {
                netCredential.Password = value;
            }
        }

        private string _model;
        /// <summary>
        /// S - 流模式 
        /// B - 块模式
        /// C - 压缩模式 
        /// </summary>
        public string Model
        {
            get { return _model; }
            set { _model = value; }
        }
        
        private string _type;
        /// <summary>
        /// I - Binary
        /// T - Text
        /// </summary>
        public string Type
        {
            get { return _type; }
            set { _type = value; }
        }

        protected NetworkStream CreateDataStream()
        {
            Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            /*
            Message = "PASV";
            if (FTPCommandHelp.IsMatchCode(Message, "22"))
            {
                sc.Connect(FTPCommandHelp.GETFormateIPEndPoint(Message_Recive));
                return new NetworkStream(sc);
            }
            */

            IPEndPoint ipp=null;
            foreach (IPAddress i in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                ipp = new IPEndPoint(i, 20000);
            }

            Message = string.Format("PORT {0}", FTPCommandHelp.FormateIPEndPoint(ipp));

            Console.Write(Message);

            sc.Bind(ipp);

            Message = "LIST";

            sc.Listen(1);
            sc = sc.Accept();

            if (FTPCommandHelp.IsMatchCode(Message, "20"))
            {
                Console.Write(new StreamReader(new NetworkStream(sc)).ReadToEnd());
                return null;
                return new NetworkStream(sc);
            }
            //530;
            return null;
        }

        /// <summary>
        /// 延时邦定数据连结通道
        /// </summary>
        protected class DataStream
        {
            protected ClientBase clientBase;
            protected Stream baseStream;
            protected string TransformMode;
            protected IPEndPoint IP;

            public DataStream(ClientBase cb)
            {
                clientBase = cb;
                {
                    TransformMode = "PASV";
                    cb.Message = TransformMode;

                    if (FTPCommandHelp.IsMatchCode(cb.Message, "227"))
                    {
                        IP = FTPCommandHelp.GETFormateIPEndPoint(cb.Message_Recive);
                        return;
                    }
                    else
                    {
                        IP = null;
                    }
                }

                foreach (IPAddress i in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    TransformMode = "PORT";
                    IP = new IPEndPoint(i, FTPCommandHelp.RandIPPort());
                    cb.Message = string.Format("PORT {0}", FTPCommandHelp.FormateIPEndPoint(IP));
                    if (FTPCommandHelp.IsMatchCode(cb.Message, "20"))
                    {
                        return;
                    }
                    else
                    {
                        IP = null;
                    }

                }
            }

            public Stream NewWorkStream
            {
                get
                {
                    if (baseStream != null)
                        return baseStream;
                    if (IP != null && TransformMode != null)
                    {
                        Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        if (TransformMode == "PASV")
                        {
                            sc.Connect(IP);
                            baseStream = new NetworkStream(sc);
                        }
                        else if (TransformMode == "PORT")
                        {
                            sc.Bind(IP);
                            sc.ReceiveTimeout = 1;
                            sc.SendTimeout = 1;
                            sc.Listen(1);
                            baseStream = new NetworkStream(sc.Accept());
                        }
                        else
                        {
                            throw new Exception();
                        }
                        return baseStream;
                    }

                    return null;
                }
            }
        }
    }

    public class ClientCommand : ClientBase
    {
        #region New

        public ClientCommand(string url, int port, string username, string userpassword, Encoding encoding) : base(url, port, username, userpassword, encoding) { }

        public ClientCommand(string url, int port, string username, string userpassword) : base(url, port, username, userpassword, Encoding.ASCII) { }

        public ClientCommand(string url, int port) : base(url, port, "anonymous", "anonymous") { }

        public ClientCommand(string url, string username, string userpassword) : base(url, 21, username, userpassword, Encoding.ASCII) { }

        #endregion

        public bool Login()
        {
            Message = string.Format("USER {0}", netCredential.UserName);
            if (!FTPCommandHelp.IsMatchCode(Message, "33"))
            {
                return false;
            }

            Message = string.Format("PASS {0}", netCredential.Password);

            return FTPCommandHelp.IsMatchCode(Message, "23");
        }

        #region Directory

        public string Directory_Current()
        {
            Message = "PWD";
            return Message;
        }

        public bool Directory_Change(string dir)
        {
            Message = string.Format("CWD {0}", dir);
            return FTPCommandHelp.IsMatchCode(Message, "25");
        }

        public bool Directory_Create(string dir)
        {
            Message = string.Format("MKD {0}", dir);
            return FTPCommandHelp.IsMatchCode(Message, "25");
        }

        public bool Directory_Delete(string dir)
        {
            Message = string.Format("RMD {0}", dir);
            return FTPCommandHelp.IsMatchCode(Message, "25");
        }

        public bool Directory_ReName(string dir_old, string dir_new)
        {
            Message = string.Format("RNFR {0}", dir_old);

            if (!FTPCommandHelp.IsMatchCode(Message, "35"))
            {
                return false;
            }

            Message = string.Format("RNTO {0}", dir_new);
            return (!FTPCommandHelp.IsMatchCode(Message, "25"));
        }

        public string Directory_List(string dir)
        {
            DataStream ds = new DataStream(this);

            if (dir == null || dir.Length == 0)
                Message = "LIST ";
            else
                Message = string.Format("LIST {0}", dir);

            return new StreamReader(ds.NewWorkStream).ReadToEnd();
        }

        #endregion

        #region



        #endregion


        #region File

        public bool File_Downing(string filename, Stream w)
        {
            DataStream ds = new DataStream(this);
            Stream r = ds.NewWorkStream;
            Message = string.Format("RETR {0}", filename);

            if (!FTPCommandHelp.IsMatchCode(Message, "1"))
            {
                return false;
            }

            byte[] b = new byte[1024];
            int l;
            l = r.Read(b, 0, b.Length);
            while (l > 0)
            {
                w.Write(b, 0, l);
                l = r.Read(b, 0, b.Length);
            }
            w.Close();
            w = null;
            if (FTPCommandHelp.IsMatchCode(Message, "2"))
            {
                return true;
            }
            return false;
        }

        public bool File_Uping(string filename, Stream r)
        {
            DataStream ds = new DataStream(this);
            Stream w = ds.NewWorkStream;
            Message = string.Format("STOR {0}", filename);

            if (!FTPCommandHelp.IsMatchCode(Message, "1"))
            {
                return false;
            }

            byte[] b = new byte[1024];
            int l;
            l = r.Read(b, 0, b.Length);
            while (l > 0)
            {
                w.Write(b, 0, l);
                l = r.Read(b, 0, b.Length);
            }
            w.Close();
            w = null;
            if (FTPCommandHelp.IsMatchCode(Message, "2"))
            {
                return true;
            }
            return false;
        }

        #endregion
    }
}
